package cn.txy.base.controller;


import cn.txy.config.R;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/minio")
public class MinIoController {
    private static final String ACCESSKEY = "admin";
    private static final String SECREKEY = "yuxiaoyuan";
    private static final String ADDRESS = "http://192.168.0.105:9000"; //访问端口号也是9090
    private static final String BUCKETNAME = "java241104";

    @PostMapping
    public R upload(@RequestPart("file") MultipartFile file) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                    //创建容器时指定的账号
                    .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                    //上传地址
                    .endpoint(MinIoController.ADDRESS).build();

            //处理文件名
            String oName = file.getOriginalFilename();
            // 的新的文件名          时间戳                     后缀名  .jpg .png
            String fileName = System.currentTimeMillis()+oName.substring(oName.lastIndexOf("."));

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(fileName)	//文件名
                    .bucket(MinIoController.BUCKETNAME)  //存储目录名
                    .stream(file.getInputStream(), file.getSize(), -1).build(); //文件流，以及大小，-1代表不分片
            //执行上传
            minioClient.putObject(putObjectArgs);
            return R.ok(ADDRESS+"/"+BUCKETNAME+"/"+fileName);
        } catch (Exception e) {
            return R.fail("上传失败");
        }
    }

    //删除文件
    @DeleteMapping("/{name}")
    public R delete(@PathVariable("name")String name) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                    //创建容器时指定的账号
                    .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                    //上传地址
                    .endpoint(MinIoController.ADDRESS).build();
            minioClient.removeObject(MinIoController.BUCKETNAME, name);
            return R.ok();
        } catch (Exception e) {
            return R.fail("删除失败");
        }
    }

}